const fs = require('fs');
const path = require('path');

// 读取处理后的GeoJSON文件
function readGeoJSONFile(filePath) {
    try {
        const data = fs.readFileSync(filePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error(`读取文件 ${filePath} 失败:`, error);
        throw error;
    }
}

// 生成树形结构数据
function generateTreeStructure() {
    try {
        // 读取处理后的村级数据
        const villageData = readGeoJSONFile('./nanjingvillage_processed.json');
        const features = villageData.features || [];
        
        // 创建树形结构的根节点
        const treeRoot = {
            name: '南京市',
            children: [],
            id: 'nanjing',
            geometry: null,
            properties: {
                level: 'city',
                totalVillages: features.length
            }
        };
        
        // 按行政区划层级组织数据
        // 1. 先按区县分组（villageCode前6位）
        const countyMap = new Map();
        
        features.forEach(feature => {
            const properties = feature.properties || {};
            const villageCode = properties.villageCode || '';
            
            if (villageCode && villageCode.length >= 9) {
                // 提取区县编码（前6位）和乡镇编码（前9位）
                const countyCode = villageCode.substring(0, 6);
                const townCode = villageCode.substring(0, 9);
                
                // 获取或创建区县节点
                if (!countyMap.has(countyCode)) {
                    countyMap.set(countyCode, {
                        name: properties.county || properties.district || `区县${countyCode}`,
                        children: [],
                        id: countyCode,
                        geometry: null,
                        properties: {
                            level: 'county',
                            countyCode: countyCode,
                            totalVillages: 0,
                            totalTowns: 0
                        }
                    });
                }
                
                const countyNode = countyMap.get(countyCode);
                
                // 在区县下按乡镇分组
                let townNode = countyNode.children.find(child => child.id === townCode);
                
                if (!townNode) {
                    townNode = {
                        name: properties.town || `乡镇${townCode}`,
                        children: [],
                        id: townCode,
                        geometry: null,
                        properties: {
                            level: 'town',
                            townCode: townCode,
                            countyCode: countyCode,
                            totalVillages: 0
                        }
                    };
                    countyNode.children.push(townNode);
                    countyNode.properties.totalTowns++;
                }
                
                // 创建村级节点
                const villageNode = {
                    name: properties.name || properties.village || `村${villageCode}`,
                    children: [], // 村级下没有子节点
                    id: villageCode,
                    geometry: feature.geometry || null,
                    properties: {
                        ...properties,
                        level: 'village',
                        villageCode: villageCode,
                        townCode: townCode,
                        countyCode: countyCode
                    }
                };
                
                townNode.children.push(villageNode);
                townNode.properties.totalVillages++;
                countyNode.properties.totalVillages++;
            }
        });
        
        // 将区县节点添加到根节点
        treeRoot.children = Array.from(countyMap.values());
        
        // 保存树形结构数据
        fs.writeFileSync(
            './nanjing_tree_structure.json',
            JSON.stringify(treeRoot, null, 2),
            'utf8'
        );
        
        console.log('树形结构数据生成成功！');
        console.log(`总区县数量: ${treeRoot.children.length}`);
        console.log(`总乡镇数量: ${treeRoot.children.reduce((sum, county) => sum + county.children.length, 0)}`);
        console.log(`总村庄数量: ${features.length}`);
        
    } catch (error) {
        console.error('生成树形结构数据失败:', error);
    }
}

// 执行生成树形结构数据
generateTreeStructure();